from odoo import fields, models, api
import requests


class MESBom(models.Model):
    _inherit = 'mrp.bom'

    @api.model_create_multi
    def create(self, vals_list):
        res = super().create(vals_list)
        for record in res:
            record.upload_drill_mes({'operation_ids': []})
        return res

    def write(self, vals):
        res = super().write(vals)
        self.upload_drill_mes(vals)
        return res

    def upload_drill_mes(self, vals):
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.drill.enabled')], limit=1).s_value
        product_id = self.product_tmpl_id
        if mes_enabled and product_id.categ_id.code in ['CHP', 'BCP', 'OPFP']:  # 成品半成品
            url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.updateImsData')]).s_value
            try:
                if 'operation_ids' in vals:
                    operation_ids = self.operation_ids.filtered(lambda x: x.is_drill_operation)
                    token = self.env['s.mes.login'].sudo().get_mes_token()
                    for operation in operation_ids:
                        data = operation.upload_drill_mes_data()
                        if not data:
                            continue
                        result = self.send(url, data, token)
                        self.env['api.records'].create({
                            'doc_type': data.get('docType', ''),
                            'api_route': url,
                            'api_params': str(data),
                            'result_json': str(result),
                            'state': 'success'
                        })
            except Exception as e:
                self.env['api.records'].create({
                    'api_route': url,
                    'doc_type': 'PROD_DRILL_PARAM',
                    'result_json': e,
                    'state': 'fail'
                })

    def send(self, url, data, token):
        headers = {
            'Content-Type': 'application/json',
            'accessToken': token,
        }
        res = requests.post(url, json=data, headers=headers)
        result = res.json()
        return result
